package com.dxj1992.intercepter;

import com.dxj1992.entity.AdminPermissions;
import com.dxj1992.entity.AdminUsers;
import com.dxj1992.exception.UnAuthException;
import com.dxj1992.intercepter.annotation.Access;
import com.dxj1992.service.IAdminPermissionsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
public class RbacInterceptor implements HandlerInterceptor {

    @Autowired
    private IAdminPermissionsService iAdminPermissionsService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 将handler强转为HandlerMethod, 前面已经证实这个handler就是HandlerMethod
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        // 从方法处理器中获取出要调用的方法
        Method method = handlerMethod.getMethod();
        // 获取出方法上的Access注解
        Access access = method.getAnnotation(Access.class);
        if (access == null) {
            // 如果注解为null, 说明不需要拦截, 直接放过
            return true;
        }

        HttpSession session = request.getSession();
        AdminUsers users = (AdminUsers) session.getAttribute("admin");
        if (users.isAdmin()){
            return true;
        }

        List<AdminPermissions> adminPermissions = iAdminPermissionsService.selectMenuByUser(users);
        Set<String> collect = adminPermissions.stream().filter(a -> !a.getPerms().equals("")).map(m -> m.getPerms()).collect(Collectors.toSet());
        for (String s : access.value()) {
            if (!collect.contains(s)) {
                throw new UnAuthException("无权访问：" + s);
            }
        }
        return true;
    }
}
